package indi.zjh.dp.access;

import indi.zjh.dp.startup.Constant;
import indi.zjh.dp.util.XMLUtil;

import java.util.HashMap;
import java.util.Map;

public class Router {
	protected Map<String, String> map = new HashMap<String, String>();
	
	public Router() throws Exception
	{		
		String[] routerList = XMLUtil.getStringList(Constant.ROUTE_CONF_FILE, "/api/router-list/url-map");
		for(int i = 0; i < routerList.length; ++i)
		{
			String[] urlmap = routerList[i].split("\\s*->\\s*");
			this.map.put(urlmap[0], urlmap[1]);
		}
		this.map.put("/ping", "indi.zjh.dp.api.PingApi");
		this.map.put("/version", "indi.zjh.dp.api.VersionApi");
		this.map.put("/classinfo", "indi.zjh.dp.api.ClassInfoApi");
	}
	
	public Api getMappedApi(String uri) throws InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		int pos = uri.indexOf("?");
		String key = null;
		if(pos == -1)
		{
			key = uri;
		}
		else
		{
			key = uri.substring(0, pos);
		}

		if(!this.map.containsKey(key))
			return null;
		
		
		String apiClassName = this.map.get(key);
		
		Api api = null;
		try
		{
			api = (Api)Class.forName(apiClassName).newInstance();
		}
		catch(Exception ee)
		{
			return null;
		}
		return api;
	}
}
